package com.bndg.browser.client

import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.webkit.JavascriptInterface
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.bndg.browser.bean.VideoBean
import com.bndg.browser.util.Trace
import com.google.gson.Gson
import com.just.agentweb.AgentWeb

/**
 * Created by cenxiaozhong on 2017/5/14.
 * source code  https://github.com/Justson/AgentWeb
 */
class AndroidInterface(private val agent: AgentWeb?, private val context: Context?) {
    companion object {
        val ACTION_DETECTED_VIDEO = "com.bndg.browser.video"
        val VIDEO_BEAN = "VIDEO_BEAN"
    }

    private val deliver = Handler(Looper.getMainLooper())


    @JavascriptInterface
    fun chickVideo(msg: String?) {
        deliver.post {
            Trace.d(">>>>", "run: $msg")
            val videoBean = Gson().fromJson(msg, VideoBean::class.java)
            videoBean?.let {
                if (videoBean.videoUrl?.isNotEmpty() == true) {
                    agent?.let {
                        val intent = Intent()
                        intent.action = VIDEO_BEAN
                        intent.putExtra(VIDEO_BEAN, videoBean)
                        LocalBroadcastManager.getInstance(context!!).sendBroadcast(intent)
                    }
                }
            }
        }
    }

    @JavascriptInterface
    fun detectedVideo(msg: String?) {
        deliver.post {
            Trace.d(">>>>", "run: $msg")
            val gson = Gson()
            val array: Array<String> = gson.fromJson(msg, Array<String>::class.java)
            val list: ArrayList<String> = ArrayList(array.toList()) // 显式创建 ArrayList
            if (list.isNotEmpty()) {
                agent?.let {
                    val intent = Intent()
                    intent.action = ACTION_DETECTED_VIDEO
                    intent.putStringArrayListExtra("videos", list) // 直接传递 ArrayList
                    LocalBroadcastManager.getInstance(context!!).sendBroadcast(intent)
                }
            }
        }
    }
}
